package my.design.synchronize;

import java.util.concurrent.locks.AbstractQueuedSynchronizer;

/**
 * @author : xusw
 * @date 2020-04-19
 */
public class TwinsLock_ {

    private final Sync sync = new Sync(2);

    private static final class Sync extends AbstractQueuedSynchronizer{

        private Sync(int count){
            if(count <=0){
                throw new IllegalArgumentException("count less then one");
            }
            setState(count);
        }
        @Override
        protected int tryAcquireShared(int arg) {
            for(;;){
                int state = getState();
                int nowState = state - arg;
                if(nowState < 0 || compareAndSetState(state,nowState)){
                    return nowState;
                }
            }
        }

        @Override
        protected boolean tryReleaseShared(int arg) {
            for(;;){
                int state = getState();
                int nowState = state + arg;
                if(compareAndSetState(state,nowState)){
                    return Boolean.TRUE;
                }
            }
        }
    }

    /**
     * 获取锁
     */
    public void lock(){
        sync.acquireShared(1);
    }

    /**
     * 释放锁
     */
    public void release(){
        sync.releaseShared(1);
    }

}
